package com.cetc.nsfx.service.sys;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/1/25 0025.
 */
@Service
public class WordLibraryService {

    public static String filePath = "E:\\word.txt";


    /**
     * @param word
     * @return 查询文件中唯一匹配的词，存在返回true，不存在返回false
     */
    public boolean findWord(String word) {
        File file = new File(filePath);
        LineIterator it = null;
        try {
            it = FileUtils.lineIterator(file, "UTF-8");
            while (it.hasNext()) {
                String line = it.nextLine();
                if(line.trim().equals(word)){
                    return true;
                }
                // do something with line
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            LineIterator.closeQuietly(it);
        }
        return false;
    }

    /**
     * @param word
     * @return 查询文件中包含word的词
     */
    public String[] suggestWord(String word) {
        File file = new File(filePath);
        LineIterator it = null;
        List<String> arr = new ArrayList<String>();
        try {
            it = FileUtils.lineIterator(file, "UTF-8");
            while (it.hasNext()) {
                String line = it.nextLine();
                if(line.contains(word)){
                    System.out.println("line="+line);
                    arr.add(line);
                }
                // do something with line
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            LineIterator.closeQuietly(it);
        }
        return (String[])arr.toArray(new String[arr.size()]);
    }

    /**
     *
     * @param word
     * @return 新增分词
     */
    public boolean addWord(String word){
        BufferedWriter bw = null;
        File file = new File(filePath);
        try {
            FileWriter fw = new FileWriter(file, true);
            bw = new BufferedWriter(fw);
            bw.write(word+"\r\n");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
